package 代理模式.JDK动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {
	public static void main(String[] args) {
		test1();
	}

	private static void test1() {
		String name = "caiya";
		final IBuyer ibuyer = new Buyer(name);
		ClassLoader classLoader = ibuyer.getClass().getClassLoader();
		Class<?>[] interfaces = ibuyer.getClass().getInterfaces();
		InvocationHandler hLambda =(Object proxy,Method method,Object[] args)->{
			Object result;
			// 这里我们在 buyTicket 操作前，进行通知操作，来模拟 buyerProxy
			if ("buyTicket".equals(method.getName())) {
				System.out.println("准备定时任务，开始刷票");
				result = method.invoke(ibuyer, args);
				System.out.println("刷票成功，短信通知客户");
			} else {
				result = method.invoke(ibuyer, args);
			}
			return result;
		};
		/*InvocationHandler h = new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object result;
				// 这里我们在 buyTicket 操作前，进行通知操作，来模拟 buyerProxy
				if ("buyTicket".equals(method.getName())) {
					System.out.println("准备定时任务，开始刷票");
					result = method.invoke(ibuyer, args);
					System.out.println("刷票成功，短信通知客户");
				} else {
					result = method.invoke(ibuyer, args);
				}
				return result;
			}
		};*/
		IBuyer proxy = (IBuyer) Proxy.newProxyInstance(classLoader, interfaces, hLambda);
		proxy.login(name, "123456");
		proxy.buyTicket();
	}

}
